package com.demon;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.rmi.server.ExportException;
import java.util.concurrent.TimeoutException;

/**
 * Created by li on 2016/10/17.
 */
public class PublicClient {
    String exchangeName;
    String exchangeType;
    Connection conn;
    Channel channel;
    public PublicClient(String virtualHost,String userName,String password,String hostName,int portNumber,
                        String exchangeName,String exchangeType) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(userName);
        factory.setPassword(password);
        factory.setVirtualHost(virtualHost);
        factory.setHost(hostName);
        factory.setPort(portNumber);
        this.exchangeType=exchangeType;
         conn = factory.newConnection();
         channel = conn.createChannel();
        channel.exchangeDeclare(exchangeName, exchangeType, true);
        this.exchangeName=exchangeName;
    }

    public void sendMsg(String routingKey,String msg) throws IOException {
        channel.basicPublish(exchangeName,routingKey,null,msg.getBytes());
        System.out.printf("send exchangeType[%s],exchangeName[%s],routingKey:[%s] message[%s] ok.....\n",
                this.exchangeType,this.exchangeName,routingKey,msg);
    }
    public void close(){
        try {
            channel.close();
        }catch (Exception e){

        }
        try {
            conn.close();
        }catch (Exception e){

        }
    }


}
